package edu.friday.service.impl;

import edu.friday.common.constant.UserConstants;
import edu.friday.common.result.TableDataInfo;
import edu.friday.model.SysUser;
import edu.friday.model.vo.SysUserVO;
import edu.friday.repository.ISysUserRepository;
import edu.friday.service.ISysUserService;
import edu.friday.utils.BeanUtils;
import edu.friday.utils.StringUtils;
import lombok.Lombok;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private ISysUserRepository iSysUserRepository;

    /**
     * 查询所有用户
     */
    @Override
    public TableDataInfo selectUserList(SysUserVO sysUserVO, Pageable pageable) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyPropertiesIgnoreEmpty(sysUserVO, sysUser);
        sysUser.setDelFlag("0");
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("userName", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("phonenumber", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<SysUser> example = Example.of(sysUser, exampleMatcher);
        Page<SysUser> all = iSysUserRepository.findAll(example, pageable);
        return TableDataInfo.success(all.toList(), all.getTotalElements());
    }

    @Override
    public String checkUsernameUnique(String username) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        return count(sysUser);
    }

    @Override
    public String checkPhoneUnique(SysUserVO sysUserVO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserVO, sysUser);
        System.out.println(sysUser);
        return checkUnique(sysUser);
    }

    @Override
    public String checkUnique(SysUser sysUser) {
        Long userId = StringUtils.isNull(sysUser.getUserId()) ? -1L : sysUser.getUserId();
        Example<SysUser> example = Example.of(sysUser);
        SysUser one = findOne(example);
        if (StringUtils.isNotNull(one) && one.getUserId().longValue() != userId.longValue())
            return UserConstants.NOT_UNIQUE;
        return UserConstants.UNIQUE;
    }

    @Override
    public SysUser findOne(Example<SysUser> example) {
        List<SysUser> list = iSysUserRepository.findAll(example, PageRequest.of(0, 1)).toList();
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public SysUser selectUserById(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setDelFlag("0");
        Optional<SysUser> one = iSysUserRepository.findOne(Example.of(sysUser));
        return one.orElse(null);

    }

    @Override
    public SysUser selectUserByUserName(String username) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        Optional<SysUser> one = iSysUserRepository.findOne(Example.of(sysUser));
        return one.orElse(null);
    }

    @Override
    public String checkEmailUnique(SysUserVO sysUserVO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserVO,sysUser);
        return checkUnique(sysUser);
    }

    @Override
    public boolean insertUser(SysUserVO sysUserVO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyPropertiesIgnoreEmpty(sysUserVO, sysUser);
        sysUser.setDelFlag("0");
        iSysUserRepository.save(sysUser);
        sysUserVO.setUserId(sysUser.getUserId());
        insertUserRole(sysUserVO);
        return null != sysUser.getUserId();
    }

    @Override
    public int deleteUserByIds(Long[] userIds) {
        return iSysUserRepository.deleteUserByIds(userIds);
    }

    @Override
    public boolean updateUser(SysUserVO sysUserVO) {
        Long userId = sysUserVO.getUserId();
        Optional<SysUser> byId = iSysUserRepository.findById(userId);
        if (!byId.isPresent())
            return false;
        iSysUserRepository.deleteUserRoleById(userId);
        SysUser sysUser = byId.get();
        BeanUtils.copyPropertiesIgnoreEmpty(sysUserVO, sysUser);
        iSysUserRepository.save(sysUser);
        insertUserRole(sysUserVO);
        return null != sysUser.getUserId();
    }

    private int insertUserRole(SysUserVO sysUserVO) {
        Long[] roles = sysUserVO.getRoleIds();
        if (StringUtils.isNull(roles) || roles.length == 0)
            return 0;
        Long[] userId = new Long[roles.length];
        Arrays.fill(userId, sysUserVO.getUserId());
        return iSysUserRepository.batchInsertUserRole(userId, roles);
    }

    public String count(SysUser sysUser) {
        Example<SysUser> example = Example.of(sysUser);
        long count = iSysUserRepository.count(example);
        if (count > 0)
            return UserConstants.NOT_UNIQUE;
        return UserConstants.UNIQUE;
    }
}
